package com.cskaoyan.service.wx.goods;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.wx.goods.GoodsListBo;
import com.cskaoyan.bean.vo.wx.auth.WxUserUtil;
import com.cskaoyan.bean.vo.wx.goods.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: bwj
 * @Date: 2022/09/09/12:00
 * @Description: 微信商品
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    private static final int RELATE_PAGES = 8;
    private static final int RELATE_LIMIT = 6;
    private static final int COMMENT_LIMIT = 6;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;

    /**
     * @Author: 宾文杰 @Description: 商品总数 @Date: 2022/9/9
     */
    @Override
    public Integer goodsCount() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        int size = marketGoods.size();
        return size;
    }

    /**
     * @Author: 宾文杰 @Description: 商品列表 @Date: 2022/9/9
     */
    @Override
    public WxGoodsListVo goodsList(GoodsListBo goodsListBo) {
        WxGoodsListVo goodsListVo = new WxGoodsListVo();
        //如果categoryId为0，则是搜索全部商品信息
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        if (goodsListBo.getOrder() != null && goodsListBo.getSort() != null) {
            marketGoodsExample.setOrderByClause(goodsListBo.getSort() + " " + goodsListBo.getOrder());
        }
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if (goodsListBo.getIsHot() != null) {
            criteria.andIsHotEqualTo(goodsListBo.getIsHot());
        }
        if (goodsListBo.getIsNew() != null) {
            criteria.andIsNewEqualTo(goodsListBo.getIsNew());
        }
        if (goodsListBo.getKeyword() != null) {
            String keyword = null;
            try {
                keyword = URLDecoder.decode(goodsListBo.getKeyword(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            criteria.andNameLike("%" + keyword + "%");
            //添加历史记录
            if (SecurityUtils.getSubject().isAuthenticated()) {
                MarketSearchHistory searchHistory = new MarketSearchHistory();
                MarketUser user = WxUserUtil.userUtil();
                searchHistory.setAddTime(new Date());
                searchHistory.setKeyword(keyword);
                searchHistory.setUpdateTime(new Date());
                searchHistory.setUserId(user.getId());
                searchHistoryMapper.insertSelective(searchHistory);
            }
        }
        if (goodsListBo.getCategoryId() != null && goodsListBo.getCategoryId() != 0) {
            criteria.andCategoryIdEqualTo(goodsListBo.getCategoryId());
        }
        if (goodsListBo.getBrandId() != null) {
            criteria.andBrandIdEqualTo(goodsListBo.getBrandId());
        }
        PageHelper.startPage(goodsListBo.getPage(), goodsListBo.getLimit());
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        //分类
        if (goodsListBo.getCategoryId() != null) {
            List<MarketGoods> marketGoods1 = categoryFilter(goodsListBo);
            ArrayList<MarketCategory> categories = new ArrayList<>();
            HashMap<Integer, MarketCategory> categoryHashMap = new HashMap<>();
            for (MarketGoods marketGood : marketGoods1) {
                Integer categoryId = marketGood.getCategoryId();
                MarketCategory category = marketCategoryMapper.selectByPrimaryKey(categoryId);
                categoryHashMap.put(categoryId, category);
            }

            for (MarketCategory value : categoryHashMap.values()) {
                categories.add(value);
            }
            goodsListVo.setFilterCategoryList(categories.toArray());
        }


        if (goodsListBo.getSort() == null && goodsListBo.getOrder() == null && goodsListBo.getCategoryId() != null) {

            //先找不是这一类别的其他类别信息
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            marketCategoryExample.createCriteria().andIdNotEqualTo(goodsListBo.getCategoryId());
            List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
            goodsListVo.setFilterCategoryList(marketCategories.toArray());
        }
        PageInfo info = new PageInfo(marketGoods);
        goodsListVo.setPage(goodsListBo.getPage());
        goodsListVo.setTotal(info.getTotal());
        goodsListVo.setPages(info.getPages());
        goodsListVo.setLimit(goodsListBo.getLimit());
        goodsListVo.setList(marketGoods.toArray());
        return goodsListVo;
    }

    private List<MarketGoods> categoryFilter(GoodsListBo goodsListBo) {
        //查询分类
        if (goodsListBo.getCategoryId() != null) {
            MarketGoodsExample marketGoodsExample1 = new MarketGoodsExample();
            if (goodsListBo.getOrder() != null && goodsListBo.getSort() != null) {
                marketGoodsExample1.setOrderByClause(goodsListBo.getSort() + " " + goodsListBo.getOrder());
            }
            MarketGoodsExample.Criteria criteria1 = marketGoodsExample1.createCriteria();
            if (goodsListBo.getIsHot() != null) {
                criteria1.andIsHotEqualTo(goodsListBo.getIsHot());
            }
            if (goodsListBo.getIsNew() != null) {
                criteria1.andIsNewEqualTo(goodsListBo.getIsNew());
            }
            if (goodsListBo.getKeyword() != null) {
                String keyword = null;
                try {
                    keyword = URLDecoder.decode(goodsListBo.getKeyword(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                criteria1.andNameLike("% " + keyword + " %");
            }
            PageHelper.startPage(goodsListBo.getPage(), goodsListBo.getLimit());
            List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(marketGoodsExample1);
            return marketGoods1;
        }
        return null;
    }

    /**
     * @Author: 宾文杰 @Description: 商品详情 @Date: 2022/9/9
     */
    @Override
    public WxGoodsDetailVo goodsDetail(Integer goodsId) {
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();
        //是商品属性
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsAttribute> marketGoodsAttributes = goodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        wxGoodsDetailVo.setAttribute(marketGoodsAttributes);

        //商品评论
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.createCriteria().andValueIdEqualTo(goodsId);
        PageHelper.startPage(1, COMMENT_LIMIT);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        PageInfo info = new PageInfo(marketComments);
        GoodsCommentVo goodsCommentVo = new GoodsCommentVo();
        goodsCommentVo.setCount((int) info.getTotal());
        goodsCommentVo.setData(marketComments.toArray());
        wxGoodsDetailVo.setComment(goodsCommentVo);

        MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
        marketGrouponRulesExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGrouponRules> marketGrouponRules = grouponRulesMapper.selectByExample(marketGrouponRulesExample);
        wxGoodsDetailVo.setGroupon(marketGrouponRules);

        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(marketIssueExample);
        wxGoodsDetailVo.setIssue(marketIssues);

        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsProduct> marketGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        wxGoodsDetailVo.setProductList(marketGoodsProducts);

        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria = goodsSpecificationExample.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        //利用hashset不重复的原理，获取商品的不同规格
        HashSet<String> hashSet = new HashSet<>();
        ArrayList<GoodsSpecVo> goodsSpecVos = new ArrayList<>();
        for (MarketGoodsSpecification goodsSpecification : goodsSpecifications) {
            hashSet.add(goodsSpecification.getSpecification());
        }
        Iterator<String> iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            String spec = iterator.next();
            GoodsSpecVo goodsSpecVo = new GoodsSpecVo();
            MarketGoodsSpecificationExample goodsSpecificationExample1 = new MarketGoodsSpecificationExample();
            MarketGoodsSpecificationExample.Criteria criteria1 = goodsSpecificationExample1.createCriteria();
            criteria1.andGoodsIdEqualTo(goodsId);
            criteria1.andSpecificationEqualTo(spec);
            List<MarketGoodsSpecification> specifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample1);
            goodsSpecVo.setName(spec);
            goodsSpecVo.setValueList(specifications);
            goodsSpecVos.add(goodsSpecVo);
        }
        wxGoodsDetailVo.setSpecificationList(goodsSpecVos);

        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        wxGoodsDetailVo.setInfo(marketGoods);
        wxGoodsDetailVo.setBrand(marketBrand);
        if (marketGoods.getShareUrl() == null || "".equals(marketGoods.getShareUrl())) {
            wxGoodsDetailVo.setShare(true);//
            wxGoodsDetailVo.setShareImage(marketGoods.getShareUrl());
        } else {
            wxGoodsDetailVo.setShare(true);
            wxGoodsDetailVo.setShareImage(marketGoods.getShareUrl());
        }

        MarketCollectExample marketCollectExample = new MarketCollectExample();
        marketCollectExample.createCriteria().andValueIdEqualTo(goodsId);
        List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(marketCollectExample);
        wxGoodsDetailVo.setUserHasCollect(marketCollects.size());
        return wxGoodsDetailVo;
    }

    /**
     * @Author: 宾文杰 @Description: 商品关联 逻辑为同一类目，为人气商品和新商品@Date: 2022/9/9
     */
    @Override
    public GoodsRelateVo goodsRelated(Integer goodsId) {
        GoodsRelateVo goodsRelateVo = new GoodsRelateVo();
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        Integer categoryId = marketGoods.getCategoryId();
        PageHelper.startPage(1, RELATE_LIMIT);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andIsHotEqualTo(true);
        criteria.andIsNewEqualTo(true);
        List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(marketGoodsExample);
        PageInfo info = new PageInfo(marketGoods1);
        goodsRelateVo.setLimit(RELATE_LIMIT);
        goodsRelateVo.setPage(1);
        goodsRelateVo.setList(marketGoods1.toArray());
        goodsRelateVo.setTotal(info.getTotal());
        goodsRelateVo.setPages(info.getPages());
        return goodsRelateVo;
    }
}
